#!/bin/sh
# postinst script for bindiff
#
# see: dh_installdeb(1)

set -e
. /usr/share/debconf/confmodule

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

bindiff_root=/opt/bindiff
bindiff_etc=/etc/opt/bindiff

case "$1" in
  configure)
    # Install .desktop file according to XDG spec.
    xdg-desktop-menu forceupdate --mode system

    # Setup install location in config file.
    /opt/bindiff/libexec/bindiff_config_setup \
      --config "${bindiff_etc}/bindiff.json" \
      "directory=${bindiff_root}" \
      "ui.java_binary=${bindiff_root}/jre/bin/java"

    if [ -x "$(which loginctl)" ]; then
      # If the system is using systemd-logind, perform per-user setup for
      # currently logged in users.
      _active_users=$(loginctl -o short-iso --no-legend | \
        awk "\$2 > ${UID_MIN:-1000} { print \$3 }")
      for _user in ${_active_users}; do
        _group=$(getent group "$(id -g "${_user}")" | cut -d: -f1)

        # Ignore failures, as these could be due to an unusual setup.
        su --login -g "${_group}" "${_user}" -c \
          "${bindiff_root}/libexec/bindiff_config_setup --per_user" || true
      done
    fi

    if [ -d /run/systemd/system ]; then
      # Note: deb-systemd-invoke does not know about --global
      systemctl --global enable bindiff-plugins.service
    fi

    echo ""
    echo "In order for the BinDiff plugins to be found by the installed"
    echo "disassemblers, symlinks need to exist in your user directory"
    echo "that point to them."
    echo "If the plugins are not found automatically, try restarting"
    echo "your user session or execute this command once as the user"
    echo "that should run BinDiff:"
    echo ""
    echo "    ${bindiff_root}/libexec/bindiff_config_setup --per_user"
    echo ""
  ;;

  abort-upgrade|abort-remove|abort-deconfigure)
  ;;

  *)
      echo "postinst called with unknown argument \`$1'" >&2
      exit 1
  ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
